<script setup>
import { ref } from "vue";
import {
  getLogin,
  getCaptcha,
  getQrcodeKey,
  getQrcodeImg,
  getQrcodeCheck,
  getUserInfoByck,
} from "../../apis/login";
import { Notifcation, RmMessage } from "../../utils/RmMessage";
import { Local } from "../../utils/storage";
import { useRouter } from "vue-router";
import { storeToRefs } from "pinia";
import { userStore } from "@/store/user";
import { getUserDetail } from "../../apis/user";
import emitter from "../../utils/eventBus";
import { getDayMusic } from "../../apis/music";
import QRCode from "qrcode";
// import QrcodeVue from "qrcode.vue";
const { loginStatus, userInfo, userId } = storeToRefs(userStore());

const router = useRouter();

const phone = ref("");
const password = ref("");
const sms = ref("");
const toSms = ref(false);
const isSend = ref(false);
const countdown = ref(60);
const timer = ref(null);
const qrCodeInformation = ref("打开网易云音乐APP扫码登录");

const dialogVisible = ref(false);
let myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;

//获取二维码
const getQrCode = () => {
  dialogVisible.value = true;
  getQrCodeKey();
};

const qrCodeKey = ref("");
const qrCodeSvg = ref("");
const getQrCodeKey = async () => {
  return getQrcodeKey().then((result) => {
    if (result.code === 200) {
      qrCodeKey.value = result.data.unikey;
      // getQrcodeImg(qrCodeKey.value).then((res) => {
      //   qrCodeSvg.value = res.data.qrurl;
      //   console.log(qrCodeSvg.value);
      // });
      QRCode.toString(
        `https://music.163.com/login?codekey=${qrCodeKey.value}`,
        {
          width: 192,
          margin: 0,
          color: {
            dark: "#335eea",
            light: "#00000000",
          },
          type: "svg",
        }
      )
        .then((svg) => {
          qrCodeSvg.value = `data:image/svg+xml;utf8,${encodeURIComponent(
            svg
          )}`;
        })
        .catch((err) => {
          console.error(err);
        })
        .finally(() => {});
    }
    checkQrCodeLogin();
  });
};
const qrCodeCheckInterval = ref();
const checkQrCodeLogin = () => {
  qrCodeCheckInterval.value = setInterval(() => {
    if (qrCodeKey.value === "") return;
    getQrcodeCheck(qrCodeKey.value).then((result) => {
      if (result.code === 800) {
        getQrCodeKey(); // 重新生成QrCode
        qrCodeInformation.value = "二维码已失效，请重新扫码";
      } else if (result.code === 802) {
        qrCodeInformation.value = "扫描成功，请在手机上确认登录";
      } else if (result.code === 801) {
        qrCodeInformation.value = "打开网易云音乐APP扫码登录";
      } else if (result.code === 803) {
        clearInterval(qrCodeCheckInterval.value);
        qrCodeInformation.value = "登录成功，请稍等...";
        // result.code = 200;
        // result.cookie = result.cookie.replace("HTTPOnly", "");
        // this.handleLoginResponse(result);
        Local.set("token", result.cookie);
        Local.set(
          "cookie",
          "MUSIC_R_T=1521617373025; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/eapi/feedback;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/neapi/feedback;;MUSIC_R_T=1521617373025; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/neapi/clientlog;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/eapi/clientlog;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/openapi/clientlog;;MUSIC_R_T=1521617373025; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/eapi/clientlog;;__csrf=9c75be29f0146dbe3aaabc910fcc41b8; Max-Age=1296010; Expires=Sat, 03 Dec 2022 03:58:22 GMT; Path=/;;MUSIC_R_T=1521617373025; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/api/clientlog;;MUSIC_SNS=; Max-Age=0; Expires=Fri, 18 Nov 2022 03:58:12 GMT; Path=/;MUSIC_R_T=1521617373025; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/weapi/feedback;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/neapi/clientlog;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/weapi/feedback;;__remember_me=true; Max-Age=1296000; Expires=Sat, 03 Dec 2022 03:58:12 GMT; Path=/;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/weapi/clientlog;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/wapi/feedback;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/wapi/clientlog;;MUSIC_U=951f07665287d0c2892a0631693c8c7c0c69186a7a4cca594d1c68f4b7a0159e993166e004087dd3878b0dffafd9fb3c0ec2d8977116d376485416a65ab4b6d850b6b67fa00974557a561ba977ae766d; Max-Age=1296000; Expires=Sat, 03 Dec 2022 03:58:12 GMT; Path=/;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/eapi/feedback;;MUSIC_R_T=1521617373025; Max-Age=2147483647; Expires=Wed, 06 Dec 2090"
        );
        getUserInfobyck();
      }
    });
  }, 1000);
};

const handleClose = () => {
  dialogVisible.value = false;
  clearInterval(qrCodeCheckInterval.value);
};

const submit = () => {
  return RmMessage.warning('目前暂不支持账号登录，请扫描二维码登录！')
  //验证码登录
  if (toSms.value) {
    console.log("验证码登录");
    if (myreg.test(phone.value) && sms.value) {
      getLogin(phone.value, password.value, sms.value).then((res) => {
        console.log(res);
        if (res.code != 200) {
          Notifcation.warning(res.msg);
        } else {
          getUser(res.profile.userId);
          Local.set("token", res.cookie);
          Local.set(
            "cookie",
            "MUSIC_R_T=1521617373025; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/eapi/feedback;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/neapi/feedback;;MUSIC_R_T=1521617373025; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/neapi/clientlog;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/eapi/clientlog;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/openapi/clientlog;;MUSIC_R_T=1521617373025; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/eapi/clientlog;;__csrf=9c75be29f0146dbe3aaabc910fcc41b8; Max-Age=1296010; Expires=Sat, 03 Dec 2022 03:58:22 GMT; Path=/;;MUSIC_R_T=1521617373025; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/api/clientlog;;MUSIC_SNS=; Max-Age=0; Expires=Fri, 18 Nov 2022 03:58:12 GMT; Path=/;MUSIC_R_T=1521617373025; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/weapi/feedback;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/neapi/clientlog;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/weapi/feedback;;__remember_me=true; Max-Age=1296000; Expires=Sat, 03 Dec 2022 03:58:12 GMT; Path=/;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/weapi/clientlog;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/wapi/feedback;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/wapi/clientlog;;MUSIC_U=951f07665287d0c2892a0631693c8c7c0c69186a7a4cca594d1c68f4b7a0159e993166e004087dd3878b0dffafd9fb3c0ec2d8977116d376485416a65ab4b6d850b6b67fa00974557a561ba977ae766d; Max-Age=1296000; Expires=Sat, 03 Dec 2022 03:58:12 GMT; Path=/;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/eapi/feedback;;MUSIC_R_T=1521617373025; Max-Age=2147483647; Expires=Wed, 06 Dec 2090"
          );
        }
      });
    } else {
      if (sms.value) {
        Notifcation.warning("请输入正确的手机号!");
      } else {
        Notifcation.warning("请输入验证码!");
      }
    }
  } else {
    console.log("密码登录");
    //手机密码登录
    if (myreg.test(phone.value) && phone.value && password.value) {
      getLogin(phone.value, password.value).then((res) => {
        console.log(res);
        if (res.code != 200) {
          Notifcation.warning(res.msg);
        } else {
          getUser(res.profile.userId);
          Local.set("token", res.cookie);
          Local.set(
            "cookie",
            "MUSIC_R_T=1521617373025; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/eapi/feedback;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/neapi/feedback;;MUSIC_R_T=1521617373025; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/neapi/clientlog;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/eapi/clientlog;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/openapi/clientlog;;MUSIC_R_T=1521617373025; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/eapi/clientlog;;__csrf=9c75be29f0146dbe3aaabc910fcc41b8; Max-Age=1296010; Expires=Sat, 03 Dec 2022 03:58:22 GMT; Path=/;;MUSIC_R_T=1521617373025; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/api/clientlog;;MUSIC_SNS=; Max-Age=0; Expires=Fri, 18 Nov 2022 03:58:12 GMT; Path=/;MUSIC_R_T=1521617373025; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/weapi/feedback;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/neapi/clientlog;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/weapi/feedback;;__remember_me=true; Max-Age=1296000; Expires=Sat, 03 Dec 2022 03:58:12 GMT; Path=/;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/weapi/clientlog;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/wapi/feedback;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/wapi/clientlog;;MUSIC_U=951f07665287d0c2892a0631693c8c7c0c69186a7a4cca594d1c68f4b7a0159e993166e004087dd3878b0dffafd9fb3c0ec2d8977116d376485416a65ab4b6d850b6b67fa00974557a561ba977ae766d; Max-Age=1296000; Expires=Sat, 03 Dec 2022 03:58:12 GMT; Path=/;;MUSIC_A_T=1521616939256; Max-Age=2147483647; Expires=Wed, 06 Dec 2090 07:12:19 GMT; Path=/eapi/feedback;;MUSIC_R_T=1521617373025; Max-Age=2147483647; Expires=Wed, 06 Dec 2090"
          );
        }
      });
    } else {
      if (password.value) {
        Notifcation.warning("请输入正确的手机号!");
      } else {
        Notifcation.warning("请输入密码!");
      }
    }
  }
};

//通过id获取用户信息
const getUser = (uid) => {
  getUserDetail({ uid: uid })
    .then(async (res) => {
      console.log(res);
      Local.set("userInfo", res.profile);
      Notifcation.success("登录成功");
      loginStatus.value = true;
      userInfo.value = res.profile;
      userId.value = res.profile.userId;
      router.push("/libaray");
      emitter.emit("updateUser");
      emitter.emit("getdaymusic");
      await getdaymusics();
      location.reload();
    })
    .catch((err) => {
      RmMessage.error(err.msg);
    });
};

//通过cookie获取用户信息
// Local.set(
//   "token",
//   "MUSIC_R_T=1460820157386; Max-Age=2147483647; Expires=Sun, 04 Mar 2091 12:28:21 GMT; Path=/neapi/clientlog; HTTPOnly;MUSIC_R_T=1460820157386; Max-Age=2147483647; Expires=Sun, 04 Mar 2091 12:28:21 GMT; Path=/openapi/clientlog; HTTPOnly;__csrf=8875cf81a463754c5c2debca73b60db3; Max-Age=1296010; Expires=Wed, 01 Mar 2023 09:14:24 GMT; Path=/;;MUSIC_A_T=1460820034686; Max-Age=2147483647; Expires=Sun, 04 Mar 2091 12:28:21 GMT; Path=/eapi/feedback; HTTPOnly;MUSIC_R_T=1460820157386; Max-Age=2147483647; Expires=Sun, 04 Mar 2091 12:28:21 GMT; Path=/neapi/feedback; HTTPOnly;MUSIC_R_T=1460820157386; Max-Age=2147483647; Expires=Sun, 04 Mar 2091 12:28:21 GMT; Path=/api/feedback; HTTPOnly;MUSIC_R_T=1460820157386; Max-Age=2147483647; Expires=Sun, 04 Mar 2091 12:28:21 GMT; Path=/wapi/clientlog; HTTPOnly;MUSIC_R_T=1460820157386; Max-Age=2147483647; Expires=Sun, 04 Mar 2091 12:28:21 GMT; Path=/weapi/clientlog; HTTPOnly;MUSIC_A_T=1460820034686; Max-Age=2147483647; Expires=Sun, 04 Mar 2091 12:28:21 GMT; Path=/api/feedback; HTTPOnly;MUSIC_A_T=1460820034686; Max-Age=2147483647; Expires=Sun, 04 Mar 2091 12:28:21 GMT; Path=/api/clientlog; HTTPOnly;MUSIC_R_T=1460820157386; Max-Age=2147483647; Expires=Sun, 04 Mar 2091 12:28:21 GMT; Path=/eapi/clientlog; HTTPOnly;MUSIC_A_T=1460820034686; Max-Age=2147483647; Expires=Sun, 04 Mar 2091 12:28:21 GMT; Path=/openapi/clientlog; HTTPOnly;MUSIC_R_T=1460820157386; Max-Age=2147483647; Expires=Sun, 04 Mar 2091 12:28:21 GMT; Path=/wapi/feedback; HTTPOnly;MUSIC_R_T=1460820157386; Max-Age=2147483647; Expires=Sun, 04 Mar 2091 12:28:21 GMT; Path=/eapi/feedback; HTTPOnly;MUSIC_R_T=1460820157386; Max-Age=2147483647; Expires=Sun, 04 Mar 2091 12:28:21 GMT; Path=/api/clientlog; HTTPOnly;MUSIC_A_T=1460820034686; Max-Age=2147483647; Expires=Sun, 04 Mar 2091 12:28:21 GMT; Path=/wapi/clientlog; HTTPOnly;MUSIC_A_T=1460820034686; Max-Age=2147483647; Expires=Sun, 04 Mar 2091 12:28:21 GMT; Path=/neapi/feedback; HTTPOnly;MUSIC_SNS=; Max-Age=0; Expires=Tue, 14 Feb 2023 09:14:14 GMT; Path=/;MUSIC_A_T=1460820034686; Max-Age=2"
// );
const getUserInfobyck = () => {
  getUserInfoByck().then(async (res) => {
    Local.set("userInfo", res.profile);
    Notifcation.success("登录成功");
    loginStatus.value = true;
    userInfo.value = res.profile;
    userId.value = res.profile.userId;
    router.push("/libaray");
    emitter.emit("updateUser");
    emitter.emit("getdaymusic");
    await getdaymusics();
    location.reload();
  });
};


const getdaymusics = async () => {
  await getDayMusic().then((res) => {
    Local.set("dayMusic", res.data.dailySongs);
  });
};

const loading = () => {
  countdown.value--;
  if (countdown.value == 0) {
    isSend.value = false;
  }
};
const clearTimer = () => {
  clearInterval(timer.value);
  timer.value = null;
};

const getCode = () => {
  if (myreg.test(phone.value)) {
    getCaptcha(phone.value).then((res) => {
      if (res.code == 200) {
        console.log(res);
        isSend.value = true;
        timer.value = setInterval(() => {
          if (countdown.value === 0) {
            clearTimer();
            isSend.value = false;
            countdown.value = 60;
          } else {
            loading();
          }
        }, 1000);
      } else {
        RmMessage.error(res.msg);
      }
    });
  } else {
    RmMessage.warning("请输入正确的手机号");
  }
};
</script>

<template>
  <div class="login_container">
    <div class="logo_wrap">
      <img
        style="width: 80px; height: 80px"
        src="../../assets/images/logo/logo2.png"
        alt=""
      />
      <!-- <el-image
        style="width: 80px; height: 80px"
        src="'../../assets/images/logo/logo2.png'"
        fit="cover"
      ></el-image> -->
    </div>
    <div class="tip">登录网易云账号</div>
    <div class="input_wrap">
      <el-input placeholder="手机号" v-model="phone">
        <template #prepend>
          <i class="iconfont icon-shouji"></i>
        </template>
      </el-input>
      <el-input
        v-show="!toSms"
        type="password"
        placeholder="密码"
        show-password
        v-model="password"
      >
        <template #prepend>
          <i class="iconfont icon-suoding"></i>
        </template>
      </el-input>
      <el-input v-show="toSms" type="text" placeholder="验证码" v-model="sms">
        <template #prepend>
          <i class="iconfont icon-yanzhengma"></i>
        </template>
        <template #append>
          <div @click="getCode" v-show="!isSend" slot="append">获取验证码</div>
          <div v-show="isSend">{{ countdown }}s</div>
        </template>
      </el-input>

      <div @click="submit" @keydown.enter="submit" class="login_btn">登录</div>
      <div class="accord">
        <div v-show="!toSms" @click="toSms = !toSms" class="tosms">
          短信登录
        </div>
        <div v-show="toSms" @click="toSms = !toSms" class="tosms">密码登录</div>
        <div @click="getQrCode" class="tosms">二维码登录</div>
      </div>
    </div>

    <el-dialog
      v-model="dialogVisible"
      width="40%"
      align-center
      :before-close="handleClose"
    >
      <div class="qr-container">
        <div v-show="qrCodeSvg" class="qr-code-container">
          <img :src="qrCodeSvg" loading="lazy" />
        </div>
        <!-- <qrcode-vue :value="qrCodeSvg" :size="150" level="H" /> -->
        <div class="qr-code-info">
          {{ qrCodeInformation }}
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.login_container {
  height: 55vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
  .logo_wrap {
    margin-top: 80px;
    padding: 50px 0;
  }
  .tip {
    font-size: 25px;
    font-weight: 600;
    margin-bottom: 50px;
  }
  .input_wrap {
    width: 400px;
    display: flex;
    flex-direction: column;
    height: 300px;
    align-items: center;
    .el-input {
      width: 320px;
      margin-bottom: 20px;
      i {
        font-size: 20px;
      }
      :deep(.el-input__suffix-inner) {
        background-color: #a5adf688;
      }
      :deep(.el-input-group__prepend) {
        background-color: #a5adf688;
        border: 0;
        border-radius: 0;
        cursor: pointer;
        transition: all 0.5s;
        &:hover {
          background-color: rgba(20, 56, 134, 0.349);
          color: #fff;
        }
        &:active {
          transform: scale(0.1);
        }
      }
      :deep(.el-input-group__append) {
        border: none;
        background-color: rgba(109, 111, 212, 0.349);
        border-radius: 0;
        cursor: pointer;
        transition: all 0.5s;
        &:hover {
          background-color: rgba(20, 56, 134, 0.349);
          color: #fff;
        }
        &:active {
          transform: scale(0.1);
        }
      }
    }
    :deep(.el-input__wrapper) {
      box-shadow: none;
      padding: 0;
      &.is-focus {
        box-shadow: none;
      }
    }
    :deep(.el-input__inner) {
      height: 45px;
      line-height: 45px;
      border: none;
      background-color: #a5adf688;
      color: #333;
      font-size: 18px;
      font-weight: 600;
    }
    .accord {
      margin-top: 20px;
      display: flex;
      width: 320px;
      justify-content: space-between;
      div {
        cursor: pointer;
        font-size: 15px;
        color: #335eea;
        border-radius: 10px;
        font-weight: 600;
      }
      .tosms {
        color: #335eea;
        border-radius: 10px;
        font-weight: 600;
        &:hover {
          text-decoration: underline;
        }
        &:active {
          transform: scale(0.9);
        }
      }
    }
    .login_btn {
      height: 45px;
      background-color: #eaeffd;
      width: 320px;
      border-radius: 8px;
      line-height: 45px;
      display: flex;
      justify-content: center;
      margin-top: 20px;
      font-size: 18px;
      font-weight: 600;
      color: #335eea;
      transition: all 0.5s;
      cursor: pointer;
      &:active {
        transform: scale(0.9);
      }
    }
  }
}
.qr-container {
  height: 350px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .qr-code-info {
    margin-top: 30px;
  }
}
</style>
